<script>
import DeviceApi from '@/api/device'

export default {
  name: 'DeviceFeedback',
  props: {
    deviceId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      feedbackList: [],
      averageRating: 0,
      totalRatings: 0,
      loading: false
    }
  },
  watch: {
    deviceId: {
      immediate: true,
      handler(newId) {
        if (newId) {
          this.fetchFeedback();
        }
      }
    }
  },
  methods: {
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    async fetchFeedback() {
      this.loading = true
      try {
        const api = new DeviceApi()
        console.log('Fetching feedback for deviceId:', this.deviceId);
        const [feedbackRes, ratingRes] = await Promise.all([
          api.getDeviceFeedback(this.deviceId),
          api.getDeviceRating(this.deviceId)
        ])
        
        console.log('Feedback response:', feedbackRes);
        console.log('Rating response:', ratingRes);
        
        if (feedbackRes.data && feedbackRes.data.code === 200) {
          this.feedbackList = (feedbackRes.data.data || []).map(feedback => ({
            ...feedback,
            is_liked: feedback.is_liked !== undefined ? feedback.is_liked : false,
            is_disliked: feedback.is_disliked !== undefined ? feedback.is_disliked : false,
            like_count: feedback.like_count !== undefined ? feedback.like_count : 0,
            dislike_count: feedback.dislike_count !== undefined ? feedback.dislike_count : 0,
          }));
          console.log('DeviceFeedback - feedbackList after fetch:', this.feedbackList);
        }
        
        if (ratingRes.data && ratingRes.data.code === 200) {
          this.averageRating = ratingRes.data.data.averageRating || 0
          this.totalRatings = ratingRes.data.data.totalRatings || 0
          console.log('Rating data:', { averageRating: this.averageRating, totalRatings: this.totalRatings });
        }
      } catch (err) {
        console.error('Error fetching feedback:', err)
        this.$myMessageBox('获取评价失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    async handleLike(feedback) {
      try {
        const api = new DeviceApi()
        const res = await api.likeFeedback(feedback.id)
        if (res.data && res.data.code === 200) {
          if (!feedback.is_liked) {
            feedback.is_liked = true;
            feedback.like_count++;
            if (feedback.is_disliked) {
              feedback.is_disliked = false;
              feedback.dislike_count--;
            }
          } else {
            feedback.is_liked = false;
            feedback.like_count--;
          }
          console.log('Feedback after like operation:', feedback);
        }
      } catch (err) {
        console.error('Error liking feedback:', err)
        this.$myMessageBox('操作失败，请稍后重试')
      }
    },
    async handleDislike(feedback) {
      try {
        const api = new DeviceApi()
        const res = await api.dislikeFeedback(feedback.id)
        if (res.data && res.data.code === 200) {
          if (!feedback.is_disliked) {
            feedback.is_disliked = true;
            feedback.dislike_count++;
            if (feedback.is_liked) {
              feedback.is_liked = false;
              feedback.like_count--;
            }
          } else {
            feedback.is_disliked = false;
            feedback.dislike_count--;
          }
          console.log('Feedback after dislike operation:', feedback);
        }
      } catch (err) {
        console.error('Error disliking feedback:', err)
        this.$myMessageBox('操作失败，请稍后重试')
      }
    }
  },
  mounted() {
    console.log('DeviceFeedback mounted with deviceId:', this.deviceId);
  }
}
</script>


<template>
  <div class="device-feedback">
    <div class="feedback-header">
      <div class="rating-summary">
        <div class="average-rating">
          <span class="rating-number">{{ averageRating.toFixed(1) }}</span>
          <div class="rating-stars">
            <span 
              v-for="star in 5" 
              :key="star"
              :class="['star', { active: star <= Math.round(averageRating) }]"
            >★</span>
          </div>
        </div>
        <div class="total-ratings">{{ totalRatings }}条评价</div>
      </div>
    </div>

    <div class="feedback-list">
      <div v-for="feedback in feedbackList" :key="feedback.id" class="feedback-item">
        <div class="feedback-user">
          <span class="user-nickname">{{ feedback.user_nickname || feedback.user_name }}</span>
          <span class="feedback-time">{{ formatDate(feedback.created_time) }}</span>
        </div>
        <div class="feedback-main-content">
          <div class="feedback-content">
            <div class="user-rating">
              <span 
                v-for="star in 5" 
                :key="star"
                :class="['star', { active: star <= feedback.rating }]"
              >★</span>
            </div>
            <p class="feedback-text">{{ feedback.feedback }}</p>
          </div>
          <div class="feedback-actions">
            <button 
              class="action-btn like-btn"
              :class="{ active: feedback.is_liked }"
              @click="handleLike(feedback)"
            >
              <img src="@/assets/like.svg" alt="点赞" class="action-icon">
              <span>{{ feedback.like_count }}</span>
            </button>
            <button 
              class="action-btn dislike-btn"
              :class="{ active: feedback.is_disliked }"
              @click="handleDislike(feedback)"
            >
              <img src="@/assets/dislike.svg" alt="踩" class="action-icon">
              <span>{{ feedback.dislike_count }}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
.device-feedback {
  margin: 20px 0;
}

.feedback-header {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rating-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.average-rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-number {
  font-size: 36px;
  font-weight: bold;
  color: #ffd700;
}

.rating-stars {
  display: inline-block;
}

.star {
  font-size: 20px;
  color: #ddd;
}

.star.active {
  color: #ffd700;
}

.total-ratings {
  color: #666;
}

.feedback-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.feedback-item {
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.feedback-user {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.user-nickname {
  font-weight: bold;
  color: #333;
}

.feedback-time {
  color: #999;
  font-size: 14px;
}

.feedback-main-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 15px;
}

.feedback-content {
  margin-bottom: 0;
  flex-grow: 1;
}

.user-rating {
  margin-bottom: 4px;
}

.feedback-text {
  color: #666;
  line-height: 1.5;
  margin: 0;
}

.feedback-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-self: flex-start;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  background: #f8f9fa;
}

.action-btn.active {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #2196f3;
}

.action-icon {
  width: 16px;
  height: 16px;
  stroke: currentColor;
  fill: none;
}

.action-btn.active .action-icon {
  stroke: #2196f3;
}

.action-btn.like-btn.active .action-icon {
  fill: #2196f3;
}

.action-btn.dislike-btn.active .action-icon {
  fill: #f44336;
}
</style> 